#include <linux/fs2.h>
#include <linux/fdtable.h>
#include <linux/sched.h>

struct file *get_empty_filp(void)
{
	// const struct cred *cred = current_cred();
	// static int old_max;
	struct file *f;

	/*
	 * Privileged users can go above max_files
	 */
	// if (get_nr_files() >= files_stat.max_files && !capable(CAP_SYS_ADMIN)) {
		/*
		 * percpu_counters are inaccurate.  Do an expensive check before
		 * we go and fail.
		 */
		// if (percpu_counter_sum_positive(&nr_files) >= files_stat.max_files)
			// goto over;
	// }

	// f = kmem_cache_zalloc(filp_cachep, GFP_KERNEL);
	f = (struct file *)kmalloc(sizeof(struct file));
	if (f == NULL)
		goto fail;

	// percpu_counter_inc(&nr_files);
	// if (security_file_alloc(f))
		// goto fail_sec;

	// INIT_LIST_HEAD(&f->f_u.fu_list);
	// atomic_long_set(&f->f_count, 1);
	// rwlock_init(&f->f_owner.lock);
	// f->f_cred = get_cred(cred);
	// spin_lock_init(&f->f_lock);
	// eventpoll_init_file(f);
	/* f->f_version: 0 */
	return f;

// over:
// 	/* Ran out of filps - report that */
// 	if (get_nr_files() > old_max) {
// 		printk(KERN_INFO "VFS: file-max limit %d reached\n",
// 					get_max_files());
// 		old_max = get_nr_files();
// 	}
// 	goto fail;

// fail_sec:
	// file_free(f);
fail:
	return NULL;
}

struct file *fget(unsigned int fd)
{
	struct file *file;
	struct files_struct *files = current->files;

	// rcu_read_lock();
	file = fcheck_files(files, fd);
	// if (file) {
		// if (!atomic_long_inc_not_zero(&file->f_count)) {
		// 	/* File object ref couldn't be taken */
		// 	rcu_read_unlock();
		// 	return NULL;
		// }
	// }
	// rcu_read_unlock();

	return file;
}

struct file *fget_light(unsigned int fd, int *fput_needed)
{
	struct file *file;
	struct files_struct *files = current->files;

	// *fput_needed = 0;
	// if ((atomic_read(&files->count) == 1)) {
		file = fcheck_files(files, fd);
	// } else {
		// rcu_read_lock();
		// file = fcheck_files(files, fd);
		// if (file) {
		// 	if (atomic_long_inc_not_zero(&file->f_count))
		// 		*fput_needed = 1;
		// 	else
		// 		/* Didn't get the reference, someone's freed */
		// 		file = NULL;
		// }
		// rcu_read_unlock();
	// }

	return file;
}
